<template>
  <view class="content">
    <view class="navbar">
      <view
        v-for="(item, index) in navList"
        :key="index"
        class="nav-item"
        :class="{ current: tabCurrentIndex === index }"
        @click="tabClick(index)"
        >{{ item.text }}</view
      >
    </view>

    <swiper
      :current="tabCurrentIndex"
      class="swiper-box"
      duration="300"
      @change="changeTab"
    >
      <swiper-item
        class="tab-content"
        v-for="(tabItem, tabIndex) in navList"
        :key="tabIndex"
      >
        <scroll-view
          class="list-scroll-content"
          scroll-y
          @scrolltolower="loadData"
        >
          <!-- 空白页 -->
          <Empty v-if="tabItem.loaded === true && orderList.length === 0" />
          <!-- 订单列表 -->
          <view
            v-for="(item, index) in orderList"
            :key="index"
            class="order-item"
          >
            <view class="i-top b-b">
              <text class="time" v-if="tabItem.state === 3">{{
                formatDate(item.selfOrder.tradeTime)
              }}</text>
              <text class="time" v-else>{{ formatDate(item.time) }}</text>
              <text class="state" :style="{ color: item.stateTipColor }">{{
                item.stateTip
              }}</text>
            </view>
            <view class="goods-box-single">
              <image
                class="goods-img"
                :src="formatImageUrl(item.mcPic)"
                mode="widthFix"
              ></image>
              <view class="right">
                <view class="right-top">
                  <text class="title clamp">{{ item.mcName }}</text>
                  <text class="attr-box"
                    >{{ item.standard }} x {{ item.numbers }}</text
                  >
                </view>
                <text class="price">{{ item.money }}</text>
                <view class="orderId">订单号：{{ item.orderNo }}</view>
                <view class="recipient">姓名：{{ item.recipientsName }}</view>
                <view class="recipient"
                  >手机号：{{ item.recipientsMobile }}</view
                >
                <view class="recipient"
                  >收获地址：{{ item.recipientsAddress }}</view
                >
                <view class="right-btn">
                  <view class="" @click="showPic(item.voucher)">
                    查看凭证
                  </view>
                </view>
              </view>
            </view>

            <view class="price-box">
              共
              <text class="num">{{ item.numbers }}</text>
              件商品 实付款
              <text class="price">{{ item.money }}</text>
            </view>
            <view class="action-box b-t" v-if="tabItem.state == 0">
              <button class="action-btn recom" @click="cancelOrder(item.id)">
                取消订单
              </button>
              <button class="action-btn recom" @click="confirmOrder(item.id)">
                确认打款
              </button>
            </view>
          </view>
          <LoadMore :status="tabItem.loadingType" />
        </scroll-view>
      </swiper-item>
    </swiper>
    <uni-popup ref="popup" type="center">
      <image
        class="popupBox"
        :src="formatImageUrl(showPics)"
        mode="widthFix"
      ></image>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { formatImageUrl, formatDate } from "@/utils/filters";
import { useUserStore } from "@/store/modules/user";
import { post } from "@/utils/request";
import LoadMore from "@/components/common/LoadMore/LoadMore.vue";
import Empty from "@/components/common/Empty/Empty.vue";

// 获取实例用于访问全局属性
const instance = getCurrentInstance();
const $rsa = instance.proxy.$rsa;
const popup = ref(null);

// 使用 store
const userStore = useUserStore();

// 当前选中的 tab 索引
const tabCurrentIndex = ref(0);

// Tab 列表
const navList = ref([
  {
    state: 0,
    text: "待打款",
    loadingType: "more",
    orderList: [],
    loaded: false,
  },
  {
    state: 1,
    text: "已完成",
    loadingType: "more",
    orderList: [],
    loaded: false,
  },
  {
    state: 2,
    text: "已取消",
    loadingType: "more",
    orderList: [],
    loaded: false,
  },
]);

// 订单列表
const orderList = ref([]);
const page = ref(1);
const showPics = ref("");

// 显示凭证图片
const showPic = (item) => {
  showPics.value = item;
  popup.value.open("top");
};

// 获取订单列表
const loadData = async (source) => {
  const index = tabCurrentIndex.value;
  const navItem = navList.value[index];
  const state = navItem.state;

  if (navItem.loadingType === "loading") {
    // 防止重复加载
    return;
  }

  navItem.loadingType = "loading";

  setTimeout(async () => {
    try {
      const res = await post("/api/merchant/merchantOrderList", {
        a_d: $rsa.encrypt(
          {
            limit: 10,
            offset: page.value,
            status: state,
            userId: userStore.userInfo?.userId,
          },
          true
        ),
        a_m: "merchant_merchantOrderList",
      });

      if (res.data?.rows) {
        for (let i = 0; i < res.data.rows.length; i++) {
          orderList.value.push(res.data.rows[i]);
        }
      }

      // loaded 新字段用于表示数据加载完毕，如果为空可以显示空白页
      navItem.loaded = true;
      page.value++;
      // 判断是否还有数据，有改为 more，没有改为 noMore
      navItem.loadingType = "more";
    } catch (error) {
      console.error("获取订单列表失败:", error);
      navItem.loadingType = "more";
    }
  }, 600);
};

// Swiper 切换
const changeTab = (e) => {
  orderList.value = [];
  page.value = 1;
  tabCurrentIndex.value = e.target.current;
  loadData("tabChange");
};

// 顶部 tab 点击
const tabClick = (index) => {
  orderList.value = [];
  page.value = 1;
  tabCurrentIndex.value = index;
};

// 确认打款
const confirmOrder = (orderTradeId) => {
  uni.showModal({
    title: "提示",
    content: "确定完成打款",
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await post("/api/merchant/confirmation", {
            a_d: $rsa.encrypt(
              {
                userId: userStore.userInfo?.userId,
                id: orderTradeId,
              },
              true
            ),
            a_m: "merchant_confirmation",
          });

          if (response.code === 2000) {
            uni.showToast({
              title: "打款已完成",
              icon: "none",
            });
            // 重新加载数据
            orderList.value = [];
            page.value = 1;
            loadData();
          }
        } catch (error) {
          console.error("确认打款失败:", error);
          uni.showToast({
            title: "操作失败",
            icon: "none",
          });
        }
      }
    },
  });
};

// 取消订单
const cancelOrder = (orderTradeId) => {
  uni.showModal({
    title: "提示",
    content: "确定取消此订单",
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await post("/api/merchant/cancelOrder", {
            a_d: $rsa.encrypt(
              {
                userId: userStore.userInfo?.userId,
                id: orderTradeId,
              },
              true
            ),
            a_m: "merchant_cancelOrder",
          });

          if (response.code === 2000) {
            uni.showToast({
              title: "成功取消订单",
              icon: "none",
            });
            // 重新加载数据
            orderList.value = [];
            page.value = 1;
            loadData();
          }
        } catch (error) {
          console.error("取消订单失败:", error);
          uni.showToast({
            title: "操作失败",
            icon: "none",
          });
        }
      }
    },
  });
};

// 订单状态文字和颜色
const orderStateExp = (state) => {
  let stateTip = "";
  let stateTipColor = "#fa436a";

  switch (+state) {
    case 1:
      stateTip = "待发货";
      break;
    case 2:
      stateTip = "待收获";
      break;
    case 9:
      stateTip = "已取消";
      stateTipColor = "#909399";
      break;
    // 更多自定义
  }

  return {
    stateTip,
    stateTipColor,
  };
};

// 页面显示时
onShow(() => {
  // 初始化用户信息
  userStore.hydrateFromStorage();
  loadData();
});
</script>

<style lang="scss">
page,
.content {
  background: $page-color-base;
  height: 100%;
}

.swiper-box {
  height: calc(100% - 40px);
}

.list-scroll-content {
  height: 100%;
}

.navbar {
  display: flex;
  height: 40px;
  padding: 0 5px;
  background: #fff;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.06);
  position: relative;
  z-index: 10;

  .nav-item {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    font-size: 15px;
    color: $font-color-dark;
    position: relative;

    &.current {
      color: $base-color;

      &:after {
        content: "";
        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translateX(-50%);
        width: 44px;
        height: 0;
        border-bottom: 2px solid $base-color;
      }
    }
  }
}

.uni-swiper-item {
  height: auto;
}

.order-item {
  display: flex;
  flex-direction: column;
  padding-left: 30upx;
  background: #fff;
  margin-top: 16upx;

  .i-top {
    display: flex;
    align-items: center;
    height: 80upx;
    padding-right: 30upx;
    font-size: $font-base;
    color: $font-color-dark;
    position: relative;

    .time {
      flex: 1;
    }

    .state {
      color: $base-color;
    }

    .del-btn {
      padding: 10upx 0 10upx 36upx;
      font-size: $font-lg;
      color: $font-color-light;
      position: relative;

      &:after {
        content: "";
        width: 0;
        height: 30upx;
        border-left: 1px solid $border-color-dark;
        position: absolute;
        left: 20upx;
        top: 50%;
        transform: translateY(-50%);
      }
    }
  }

  /* 多条商品 */
  .goods-box {
    height: 160upx;
    padding: 20upx 0;
    white-space: nowrap;

    .goods-item {
      width: 120upx;
      height: 120upx;
      display: inline-block;
      margin-right: 24upx;
    }

    .goods-img {
      display: block;
      width: 100%;
      height: 100%;
    }
  }

  /* 单条商品 */
  .goods-box-single {
    display: flex;
    padding: 20upx 0;

    .goods-img {
      display: block;
      width: 170upx;
      height: 170upx;
    }

    .right {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 0 30upx 0 24upx;
      overflow: hidden;

      .right-top {
        display: flex;
        padding-bottom: 10rpx;

        .title {
          font-size: $font-base + 2upx;
          color: $font-color-dark;
          line-height: 1;
          max-width: 50%;
          // overflow: hidden;
        }

        .attr-box {
          font-size: $font-sm + 2upx;
          color: $font-color-light;
          padding: 0 12upx;
        }
      }

      .orderId {
        font-size: $font-sm + 2upx;
        color: $font-color-light;
        padding: 20rpx 0 12upx;
      }

      .recipient {
        font-size: $font-sm + 2upx;
        color: $font-color-light;
      }

      .price {
        font-size: $font-base + 2upx;
        color: $font-color-dark;

        &:before {
          content: "￥";
          font-size: $font-sm;
          margin: 0 2upx 0 8upx;
        }
      }

      .right-btn {
        display: flex;
        justify-content: flex-end;
        padding-top: 10px;

        view {
          width: 160upx;
          height: 50upx;
          text-align: center;
          line-height: 50upx;
          background: #148744;
          border-radius: 5px;
          font-size: 24rpx;
          color: #fff;
        }
      }
    }
  }

  .price-box {
    display: flex;
    justify-content: flex-end;
    align-items: baseline;
    padding: 20upx 30upx;
    font-size: $font-sm + 2upx;
    color: $font-color-light;

    .num {
      margin: 0 8upx;
      color: $font-color-dark;
    }

    .price {
      font-size: $font-lg;
      color: $font-color-dark;

      &:before {
        content: "￥";
        font-size: $font-sm;
        margin: 0 2upx 0 8upx;
      }
    }
  }

  .action-box {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 100upx;
    position: relative;
    padding-right: 30upx;
  }

  .action-btn {
    width: 160upx;
    height: 60upx;
    margin: 0;
    margin-left: 24upx;
    padding: 0;
    text-align: center;
    line-height: 60upx;
    font-size: $font-sm + 2upx;
    color: $font-color-dark;
    background: #fff;
    border-radius: 100px;

    &:after {
      border-radius: 100px;
    }

    &.recom {
      background: #fff9f9;
      color: $base-color;

      &:after {
        border-color: #f7bcc8;
      }
    }
  }
}

/* load-more */
.uni-load-more {
  display: flex;
  flex-direction: row;
  height: 80upx;
  align-items: center;
  justify-content: center;
}

.uni-load-more__text {
  font-size: 28upx;
  color: #999;
}

.uni-load-more__img {
  height: 24px;
  width: 24px;
  margin-right: 10px;
}

.uni-load-more__img > view {
  position: absolute;
}

.uni-load-more__img > view view {
  width: 6px;
  height: 2px;
  border-top-left-radius: 1px;
  border-bottom-left-radius: 1px;
  background: #999;
  position: absolute;
  opacity: 0.2;
  transform-origin: 50%;
  animation: load 1.56s ease infinite;
}

.uni-load-more__img > view view:nth-child(1) {
  transform: rotate(90deg);
  top: 2px;
  left: 9px;
}

.uni-load-more__img > view view:nth-child(2) {
  transform: rotate(180deg);
  top: 11px;
  right: 0;
}

.uni-load-more__img > view view:nth-child(3) {
  transform: rotate(270deg);
  bottom: 2px;
  left: 9px;
}

.uni-load-more__img > view view:nth-child(4) {
  top: 11px;
  left: 0;
}

.load1,
.load2,
.load3 {
  height: 24px;
  width: 24px;
}

.load2 {
  transform: rotate(30deg);
}

.load3 {
  transform: rotate(60deg);
}

.load1 view:nth-child(1) {
  animation-delay: 0s;
}

.load2 view:nth-child(1) {
  animation-delay: 0.13s;
}

.load3 view:nth-child(1) {
  animation-delay: 0.26s;
}

.load1 view:nth-child(2) {
  animation-delay: 0.39s;
}

.load2 view:nth-child(2) {
  animation-delay: 0.52s;
}

.load3 view:nth-child(2) {
  animation-delay: 0.65s;
}

.load1 view:nth-child(3) {
  animation-delay: 0.78s;
}

.load2 view:nth-child(3) {
  animation-delay: 0.91s;
}

.load3 view:nth-child(3) {
  animation-delay: 1.04s;
}

.load1 view:nth-child(4) {
  animation-delay: 1.17s;
}

.load2 view:nth-child(4) {
  animation-delay: 1.3s;
}

.load3 view:nth-child(4) {
  animation-delay: 1.43s;
}

@-webkit-keyframes load {
  0% {
    opacity: 1;
  }

  100% {
    opacity: 0.2;
  }
}

.popupBox {
  text-align: center;
}
</style>
